layui.use(["jquery","layer","form",'upload'],function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var upload = layui.upload;

    classification = function classification(){
        layer.open({
            type:2,
            title:"选择分类",
            area:["500px","500px"],
            offset:['180px','550px'],
            content:"product-addProduct-classification.html",
        });
    }

    var urlArr = new Array();
    upload.render({
        elem:"#upLoad",
        url:"/Upload/uploadFiles",
        field:'file',
        accept:'file',
        auto:false,
        bindAction:'#queding',
        multiple:true,
        choose: function(obj){//走缓存
            //将每次选择的文件追加到文件队列
            var files = obj.pushFile();
            //预读本地文件，如果是多文件，则会遍历。(不支持ie8/9)
            obj.preview(function(index, file, result){
                if (file.size > 0 && $('#imgurls').find('img').length === 0) {
                    $('#imgurls').empty();
                }
                // 添加图片 ImgPreview-预览的dom元素的id
                $('#imgurls').append('<div style="float: left;" class="file-iteme" id="container' + index + '"><div class="handle"><i id="upload_img_' + index + '" class="layui-icon" style="color: white ;margin-right: 40%">&#xe640;</i></div>' +
                    '<img id="showImg' + index + '" style="cursor:pointer;"src="' + result + '" alt="' + file.name + '"></div>');
                //删除某图片
                $("#upload_img_" + index).bind('click', function () {
                    delete files[index];
                    $("#container"+index).remove();
                });

            });
        },
        done: function (res) {
            urlArr.push(res.data);
        },
        allDone: function(){
            $("#SubmitProduct").click();
        }
    });

    $(document).on("mouseenter mouseleave", ".file-iteme", function (event) {
        if (event.type === "mouseenter") {
            //鼠标悬浮
            $(this).children(".handle").fadeIn("fast");
        } else if (event.type === "mouseleave") {
            //鼠标离开
            $(this).children(".handle").hide();
        }
    });

    var recommend = 3;//新品推荐
    var discount = 3;//可用优惠券
    var ensure = 4;//服务保证
    form.on("radio(recommend)",function (data) {
        if (data.value == "新品"){
            recommend = 2;
        }else {
            recommend = 3;
        }
    });

    form.on("radio(discount)",function (data) {
        if (data.value == "是"){
            discount = 2;
        }else {
            discount = 3;
        }
    });

    form.on("radio(ensure)",function (data) {
        if (data.value == "无忧退货"){
            ensure = 2;
        }else if(data.value =="快速退款") {
            ensure = 3;
        }else{
            ensure = 4;
        }
    });

    //现在时间
    function getTime(){
        var date=new Date();
        var year=date.getFullYear();
        var month=date.getMonth()+1;
        var day=date.getDate();
        var hour=date.getHours();
        var minute=date.getMinutes();
        var second=date.getSeconds();
        var dateStr = year+"-"+zeroFilling(month)+"-"+zeroFilling(day)+" "+zeroFilling(hour)+":"+zeroFilling(minute)+":"+zeroFilling(second);
        $('#currentTime').val(dateStr);
    }

    function zeroFilling(data){
        if(data<10){
            data="0"+data;
        }
        return data;
    }

    $("#SubmitProduct").click(function () {
        for (var i = 0; i < urlArr.length; i++) {
            if (i == 0) {
                $("#mainImage").val(urlArr[i]);
            }
        }
         getTime();
         //商品分类
         var categroyId = $("#categroyId").val();
         //商品名称
         var productName = $("#productName").val();
         //商品介绍
         var productDescription = $("#productDescription").val();
         //商品标签
         var productLabel = $("#productLabel").val();
         //商品货号
         var productCode = $("#productCode").val();
         //商品售价
         var currentpriceProduct = $("#currentpriceProduct").val();
         //商品原价
         var originalpriceProduct = $("#currentpriceProduct").val();
         //关键字
         var searchKeywords = $("#searchKeywords").val();
         //上传图片路径
         var mainImage = $("#mainImage").val();
         //当前时间
         var currentTime = $("#currentTime").val();
         var user = JSON.parse(localStorage.getItem('user'));
         var userId = user.data.userId;
         $.ajax({
             url:"/product/getProductCode",
             data:{},
             type:'post',
             dataType:"json",
             success:function (data) {
                 var arr = [];
                 for (var i = 0; i < data.data.length ; i++) {
                     arr.push(data.data[i].productCode);
                 }
                 var num = 0;
                 for (var i = 0; i <= arr.length ; i++) {
                     if (arr[i] == productCode) {
                         layer.msg("已存在商品编号");
                         return ;
                     }
                     if (arr[i] != productCode&&arr.length!=0) {
                         num++;
                     }
                     if (num == arr.length) {
                         var param = {
                             "categroyId":categroyId,
                             "productName":productName,
                             "productDescription":productDescription,
                             'productLabel':productLabel,
                             'productCode':productCode,
                             "currentpriceProduct":currentpriceProduct,
                             "originalpriceProduct":originalpriceProduct,
                             "searchKeywords":searchKeywords,
                             "mainImage":mainImage,
                             "recommend":recommend,
                             "discount":discount,
                             "ensure":ensure,
                             'createDate':currentTime,
                             'createId':userId
                         };
                         $.ajax({
                             url:"/product/addProduct",
                             data:param,
                             type:'post',
                             dataType:'text',
                             success:function (data) {
                                 $.ajax({
                                     url:"/product/getproductId",
                                     data:{"productCode":productCode},
                                     type:'post',
                                     dataType:'json',
                                     success:function (data) {
                                         var examine={
                                             'launchId':userId,
                                             'applyDate':currentTime,
                                             'result':2,
                                             'courseId':data.data.productId
                                         }
                                         $.ajax({
                                             url:"/SyCourseRecord/addProductRecord",
                                             data:examine,
                                             type:'post',
                                             dataType:'text',
                                             success:function (data) {
                                                 layer.msg("添加成功，待审核");
                                                 window.location.replace('/product/productManage/productList/product-list.html')
                                             }
                                         })
                                     }
                                 })
                             }
                         })
                     }
                 }
             }
         })
    });

    refresh=function refresh(){
        location.reload();
    }

    //返回按钮
    $('#goBack').click(function () {
        var title = $('#title').text();
        var iframe = parent.$('.iframe');
        $.each(iframe,function (i,item) {
            if(title == $(item).attr('_href')){
                parent.$('#beforeHref').val($(item).attr('_href'));
                parent.beforeHref();
                return;
            }
        });
    });

    //点击后父页面右键关闭选项卡元素隐藏
    $(document).click(function () {
        parent.$('.tab').hide();
    });

})